package org.hackystat.devcathlon.ui;

import java.util.TimerTask;
import java.util.logging.Logger;
import javax.xml.datatype.XMLGregorianCalendar;
import org.hackystat.devcathlon.engine.event.Event;
import org.hackystat.devcathlon.engine.event.EventException;
import org.hackystat.devcathlon.engine.event.EventScore;
import org.hackystat.devcathlon.engine.event.EventScoreManager;
import org.hackystat.devcathlon.engine.match.Match;
import org.hackystat.devcathlon.engine.match.MatchManager;
import org.hackystat.devcathlon.engine.team.Team;
import org.hackystat.utilities.logger.HackystatLogger;
import org.hackystat.utilities.tstamp.Tstamp;

/**
 * EventSchedule class schedules events to run.
 * 
 * @author John Zhou
 */
public class EventTask extends TimerTask {
  /** The event to be run. */
  private Event event;
  /** The match of the event. */
  private Match match;
  /** Holds the HackystatLogger for this Service. */
  private Logger logger;

  /**
   * Instantiates an EventSchedule.
   * 
   * @param match The match of the event.
   * @param event The event to be scheduled.
   */
  public EventTask(Match match, Event event) {
    this.logger = HackystatLogger.getLogger("org.hackystat.devcathlon", "devcathlon");
    this.match = match;
    this.event = event;
  }

  /**
   * Runs the scheduled task.
   */
  @Override
  public void run() {
    XMLGregorianCalendar time = Tstamp.makeTimestamp();
    try {
      if (time.compare(match.getEndTime()) < 0) {
        for (Team team : match.getTeams()) {
          EventScore eventScore = event.computeScore(match, team, time);
          eventScore = EventScoreManager.getInstance().updateEventScore(eventScore);
          match.addScore(eventScore, event);
          MatchManager.getInstance().updateMatch(match);
          logger.info("Finished getting Event score");
        }
      }
    }
    catch (EventException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
